import logging
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtWidgets import QMessageBox
from moviepy.editor import VideoFileClip

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')


class Worker_Main(QThread):
    finished = pyqtSignal(str)  # 定义完成信号
    # error_info = pyqtSignal(str)

    def __init__(self, video_path: str, audio_path: str, codec: str = 'libmp3lame'):
        super(Worker_Main, self).__init__()
        self.video_path = video_path
        self.audio_path = audio_path
        self.codec = codec

    def run(self):
        try:
            self.extract_audio()
            # 使用 self 来引用当前实例的 print_finished 方法
            self.finished.emit("Audio extraction completed successfully")
        except Exception as e:
            self.finished.emit(str(e))
        # worker.finished.connect(self.print_finished)

    def extract_audio(self):
        clip = VideoFileClip(self.video_path)
        try:
            logging.info("Video duration: %s", clip.duration)
            audio = clip.audio
            audio.write_audiofile(self.audio_path, codec=self.codec)
        except Exception as e:
            # QMessageBox.warning(None, "格式错误", f"目前暂不支持转换为{self.codec}")
            logging.info(str(e))
            raise e
        #     # self.error_info.emit(f'目前暂不支持转换为{str(e)}')
        finally:
            clip.close()  # 确保释放资源

    # 槽函数，处理完成信号
    def print_finished(self, message):
        logging.info("Audio extraction completed and thread has finished: %s", message)


# 测试 Worker_Main 线程
if __name__ == '__main__':
    video_path = './resources/Da Da Da.mp4'
    audio_path = './resources/Da Da Da.mp3'
    worker = Worker_Main(video_path, audio_path)  # 创建 Worker_Main 线程实例
    worker.start()  # 启动线程
    worker.wait()  # 等待线程结束
    logging.info("Main thread has finished waiting for the worker thread.")  # 确认主线程等待结束
